<template>
  <div class="container">
    <div class="map" style="height: calc(100% - 1% - 40px);" ref="map"></div>
    <div class="icons">
      <div class="icon" v-for="item in iconOptions" :key="item.name">
        <img :src="item.icon" alt="">
        <div class="name">{{ item.name }}</div>
      </div>
    </div>
  </div>
</template>
<script>
import { getVideoUrl } from "@/api/system/area";
import { getMapEmployeeList, getMapCarList } from '@/api/bigScreen.js';
import { getMapInstance, defaultMapOptions } from '@/utils/map.js';
import employeesIcon from '@/assets/images/bigScreen/worker.png';
import carsIcon from '@/assets/images/bigScreen/workCar.png';
import platformsIcon from '@/assets/images/bigScreen/sanitation.png';
import bucketsIcon from '@/assets/images/bigScreen/buckets.png';

import employeesGreenIcon from '@/assets/images/bigScreen/icon/green_work.png';
import employeesRedIcon from '@/assets/images/bigScreen/icon/red_work.png';
import employeesWarnIcon from '@/assets/images/bigScreen/icon/warn_work.png';
import carsGreenIcon from '@/assets/images/bigScreen/icon/green_workCar.png';
import carsRedIcon from '@/assets/images/bigScreen/icon/red_workCar.png';
import platformsGreenIcon from '@/assets/images/bigScreen/icon/green_sanitation.png';
import platformsRedIcon from '@/assets/images/bigScreen/icon/red_sanitation.png';
// 垃圾桶暂时没有图标
// import bucketsGreenIcon from '@/assets/images/bigScreen/icon/green_work.png';
// import bucketsRedIcon from '@/assets/images/bigScreen/icon/green_work.png';
import green_box from '@/assets/images/bigScreen/icon/green_title.png';
import red_box from '@/assets/images/bigScreen/icon/red_title.png';
import green_long_box from '@/assets/images/bigScreen/icon/green_long_title.png';
import red_long_box from '@/assets/images/bigScreen/icon/red_long_title.png';
import personImg from '@/assets/images/bigScreen/bottom/person.png';
import carImg from '@/assets/images/bigScreen/bottom/car.png';
import hwImg from '@/assets/images/bigScreen/bottom/hw.png';

import waterImg from '@/assets/images/bigScreen/icon/water.png';
import hhImg from '@/assets/images/bigScreen/icon/hh.png';
import dealImg from '@/assets/images/bigScreen/icon/deal.png';
import growImg from '@/assets/images/bigScreen/icon/grow.png';

import Hls from 'hls.js';

const mediaBaseUrl = process.env.VUE_APP_CDN_HOST;

export default {
  name: "BigScreenCenter",
  components: {},
  props: {
    data: {
      type: Object,
      default: () => ({}),
    },
    areaId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    return {
      map: null,
      areaPolygons: [],
      ploygonText: [],
      markers: [],
      employeesMarkers: [],
      carsMarkers: [],
      platformsMarkers: [],
      bucketsMarkers: [],
      iconOptions: [
        {
          name: '作业人员',
          icon: personImg,
        },
        {
          name: '作业车辆',
          icon: carImg,
        },
        {
          name: '环卫站',
          icon: hwImg,
        },
        // {
        //   name: '垃圾箱',
        //   icon: bucketsIcon,
        // },
      ],
      currentAction: null,
      lineString: null,
      isAreaChanged: false, // 添加区域切换标志
    };
  },
  computed: {
    // 作业人员
    employees() {
      return this.data?.employees?.filter(item => item.location) ?? [];
    },
    // 作业车辆
    cars() {
      return (this.data?.cars?.filter(item => item.location) ?? []).map(item => {
        item.type = 'cars';
        return item;
      });
    },
    // 环卫站
    platforms() {
      return (this.data?.platforms?.filter(item => item.location) ?? []).map(item => {
        item.type = 'platforms';
        return item;
      });
    },
    // 垃圾箱
    buckets() {
      return this.data?.buckets?.filter(item => item.location) ?? [];
    },
    // 区域
    area() {
      const areas = this?.data?.area;
      if (!areas) return [];
      if (Array.isArray(areas)) return areas;
      return [areas]?.filter(item => item?.areaLocations?.length) ?? [];
    },
  },
  watch: {
    data(newVal) {
      setTimeout(() => {
        this.createMarkers();
        // 每次数据刷新时都清除和重新绘制Polygon，确保没有残留
        this.createAmapPolygon();
      }, 500)
    },
    areaId() {
      // 区域切换时清理信息窗口状态
      this.currentAction = null;
      if (window.currentCustomInfoWindow && window.currentCustomInfoWindow.parentNode) {
        window.currentCustomInfoWindow.parentNode.removeChild(window.currentCustomInfoWindow);
        window.currentCustomInfoWindow = null;
      }
      this.isAreaChanged = true; // 设置区域切换标志
    },
  },
  async mounted() {
    this.$bus.$on('changeMapView', this.flyTo);

    // 高德地图初始化
    try {
      const AMap = await getMapInstance(['AMap.Marker', 'AMap.InfoWindow', 'AMap.Polygon', 'AMap.Polyline']);
      this.AMap = AMap;
      this.map = new AMap.Map(this.$refs.map, {
        ...defaultMapOptions,
        zoom: 15,
        mapStyle: 'amap://styles/darkblue'
      });

      // 添加地图点击事件来关闭自定义信息窗口和轨迹
      this.map.on('click', () => {
        // 关闭自定义信息窗口
        if (window.currentCustomInfoWindow && window.currentCustomInfoWindow.parentNode) {
          window.currentCustomInfoWindow.parentNode.removeChild(window.currentCustomInfoWindow);
          document.removeEventListener('click', window.currentInfoWindowCloseHandler);
          window.currentCustomInfoWindow = null;
        }
        // 关闭轨迹
        this.closeTrack();
      });

      console.log('高德地图初始化成功');
    } catch (error) {
      console.error('高德地图初始化失败:', error);
    }
    // map.on('load', () => {
    //   const lineString = new aimap.LineString({
    //     data:[],
    //     zIndex: 99,
    //     style: {
    //       'line-width': 3,
    //       'line-color': '#ff6f00',
    //       'line-join': 'round',
    //     },
    //     map
    //   });
    //   this.lineString = lineString;
    //   window.lineString = lineString;
    // });
  },
  beforeDestroy() {
    this.$bus.$off('changeMapView', this.flyTo);
    // 清理自定义信息窗口
    if (window.currentCustomInfoWindow && window.currentCustomInfoWindow.parentNode) {
      window.currentCustomInfoWindow.parentNode.removeChild(window.currentCustomInfoWindow);
      document.removeEventListener('click', window.currentInfoWindowCloseHandler);
      window.currentCustomInfoWindow = null;
    }
  },
  methods: {
    // 创建标记
    createMarkers() {
      const markers = [...this.markers];
      if (markers?.length) {
        // 高德地图-清除上一次的标记
        this.markers.forEach(marker => marker.setMap(null));
        this.employeesMarkers = [];
        this.carsMarkers = [];
        this.platformsMarkers = [];
        this.bucketsMarkers = [];
        this.markers = [];
      }
      const employeesMarkers = this.drawEmployeesMarker();
      const cars = this.drawCars();
      const platforms = this.drawPlatforms();
      // const buckets = this.drawbuckets();
      this.employeesMarkers = employeesMarkers;
      this.carsMarkers = cars;
      this.platformsMarkers = platforms;
      // this.bucketsMarkers = buckets;
      // this.markers = [...employeesMarkers, ...cars, ...platforms, ...buckets];
      this.markers = [...employeesMarkers, ...cars, ...platforms];

      // 数据刷新后恢复已打开的信息窗口
      this.restoreOpenInfoWindow();
    },
    createMarkerEl(icon, title, id, type, data) {
      const that = this;
      const customData = JSON.stringify(data);
      const el = document.createElement('div');
      el.setAttribute('data-id', id);
      el.setAttribute('data-customData', customData);
      el.setAttribute('data-type', type);
      el.addEventListener('click', function (e) {
        const target = e.target;
        const dataset = target.dataset;
        const { customdata: newData = '', type = '' } = dataset;
        if (!type) return false;
        const res = JSON.parse(newData);
        that.currentAction = {
          type,
          data: res,
        };
      });
      // <div data-customData=${customData} data-type="${type}" style="color: #fff;font-size: 14px;padding:5px 10px;width: max-content;border: 2px solid #00e676;position: absolute;top: -30px;left: 50%;transform: translateX(-50%);">${title}</div>
      // el.style = 'position: relative;width: max-content;cursor: pointer;';
      el.style = 'width: max-content;cursor: pointer;';
      el.innerHTML = `
      <img data-customData=${customData} data-type="${type}" src=${icon} style="height: 30px;width: 30px;cursor: pointer;">
      `;
      return el;
    },
    createAmapMarker(position, icon, title, id, data, type, offset = '') {
      const el = this.createMarkerEl(icon, title, id, type, data);
      const marker = new this.AMap.Marker({
        position: position,
        content: el,
        anchor: 'bottom-center'
      });
      this.markers.push(marker);
      marker.setMap(this.map);
      return marker;
    },
    setPlatformsChart(capacity, disposalToday, disposalThisMonth, disposalGrowth) {
      return `
        <div style="display: flex;flex-wrap: wrap;justify-content: flex-start;gap: 8px;width: 100%;height: 100%;">
        <div class="chart-item-hover" style="position: relative;height: 100%;flex: 1;min-width: 100px;cursor: pointer;transition: all 0.3s ease;border-radius: 8px;overflow: hidden;">
          <img src="${waterImg}" style="object-fit: cover;height: 100%;width: 100%;transition: transform 0.3s ease;">
          <div style="font-weight: bold;font-size: 15px;color: #fff;position: absolute;top: 45%;left: 50%;transform: translateX(-50%);transition: all 0.3s ease;">${capacity}%</div>
          <div style="color: #fff;font-size: 11px;position: absolute;left: 50%;transform: translateX(-50%);top: 80%;transition: all 0.3s ease;">已用容量(%)</div>
        </div>
        <div class="chart-item-hover" style="position: relative;height: 100%;flex: 1;min-width: 100px;cursor: pointer;transition: all 0.3s ease;border-radius: 8px;overflow: hidden;">
          <img src="${hhImg}" style="object-fit: cover;height: 100%;width: 100%;transition: transform 0.3s ease;">
          <div style="font-weight: bold;font-size: 15px;color: #fff;position: absolute;top: 45%;left: 50%;transform: translateX(-50%);transition: all 0.3s ease;">${disposalToday}m³</div>
          <div style="color: #fff;font-size: 11px;position: absolute;left: 50%;transform: translateX(-50%);top: 80%;white-space: nowrap;transition: all 0.3s ease;">今日处理垃圾</div>
        </div>
        <div class="chart-item-hover" style="position: relative;height: 100%;flex: 1;min-width: 100px;cursor: pointer;transition: all 0.3s ease;border-radius: 8px;overflow: hidden;">
          <img src="${dealImg}" style="object-fit: cover;height: 100%;width: 100%;transition: transform 0.3s ease;">
          <div style="font-weight: bold;font-size: 15px;color: #fff;position: absolute;top: 45%;left: 50%;transform: translateX(-50%);transition: all 0.3s ease;">${disposalThisMonth}m³</div>
          <div style="color: #fff;font-size: 11px;position: absolute;left: 50%;transform: translateX(-50%);top: 80%;white-space: nowrap;transition: all 0.3s ease;">本月处理垃圾</div>
        </div>
        <div class="chart-item-hover" style="position: relative;height: 100%;flex: 1;min-width: 100px;cursor: pointer;transition: all 0.3s ease;border-radius: 8px;overflow: hidden;">
          <img src="${growImg}" style="object-fit: cover;height: 100%;width: 100%;transition: transform 0.3s ease;">
          <div style="font-weight: bold;font-size: 15px;color: #fff;position: absolute;top: 45%;left: 50%;transform: translateX(-50%);transition: all 0.3s ease;">${disposalGrowth}m³</div>
          <div style="color: #fff;font-size: 11px;position: absolute;left: 50%;transform: translateX(-50%);top: 80%;white-space: nowrap;transition: all 0.3s ease;">垃圾增长量</div>
        </div>
</div>
      `;
      // <div class="chart-item-hover" style="position: relative;height: 100%;flex: 1;min-width: 100px;cursor: pointer;transition: all 0.3s ease;border-radius: 8px;overflow: hidden;">
      //     <img src="${dealImg}" style="object-fit: cover;height: 100%;width: 100%;transition: transform 0.3s ease;">
      //     <div style="font-weight: bold;font-size: 15px;color: #fff;position: absolute;left: 50%;transform: translateX(-50%);top: 25%;transition: all 0.3s ease;">${disposalThisMonth}m³</div>
      //     <div style="color: #fff;font-size: 11px;position: absolute;left: 50%;transform: translateX(-50%);top: 35%;white-space: nowrap;transition: all 0.3s ease;">本月处理垃圾</div>
      //   </div>
      //   <div class="chart-item-hover" style="position: relative;height: 100%;flex: 1;min-width: 100px;cursor: pointer;transition: all 0.3s ease;border-radius: 8px;overflow: hidden;">
      //     <img src="${growImg}" style="object-fit: cover;height: 100%;width: 100%;transition: transform 0.3s ease;">
      //     <div style="font-weight: bold;font-size: 15px;color: #CB3F3E;position: absolute;left: 50%;transform: translateX(-50%);top: 25%;transition: all 0.3s ease;">${disposalGrowth}m³</div>
      //     <div style="color: #fff;font-size: 11px;position: absolute;left: 50%;transform: translateX(-50%);top: 35%;white-space: nowrap;transition: all 0.3s ease;">垃圾增长量</div>
      //   </div>
    },
    async addMarkPopup(marker, data, type, address = '') {
      let url = '', options = [];
      const { name, id, number, photo = '', location, alarms, locationTime, isCamera } = data;
      const time = locationTime ? new Date(locationTime).toLocaleString() : '';
      const { longitude, latitude } = location;
      const messageValue = (alarms || []).map(item => item?.messageValue || '').join(','); // 警告信息
      let isAbnormal = false; // 是否异常

      let isAutoH = false;
      let chartStr = '';
      switch (type) {
        case 'employees':
          const {
            downTime,
            upTime,
            attendanceStatus,
            attendanceWorkTime,
            attendanceWorkDay,
            employeeStatus,
            workingMileage,
            attendanceMap,
            phone,
          } = data;
          isAbnormal = !!employeeStatus;

          const attendanceOptions = {
            0: '正常',
            1: '迟到',
            2: '旷工',
            3: '请假',
            4: '异常',
            5: '休息',
          };
          const attendanceStr = attendanceOptions[attendanceStatus] || '';
          const { 0: normal = 0, 2: late = 0, 5: leave = 0 } = attendanceMap || {};
          // 人员
          options = [
            {
              name: '姓名：',
              value: name,
              type: 'name',
            },
            {
              name: '考勤状态：',
              value: attendanceStr,
              setStyle: (val) => {
                const color = val == '正常' ? '#07DF9F' : '#CB3F3E';
                return `color:${color};`;
              },
            },
            {
              name: '身体状况：',
              value: `${employeeStatus ? '异常' : '健康'}`,
              setStyle: (val) => {
                const color = val == '健康' ? '#07DF9F' : '#CB3F3E';
                return `color:${color};`;
              },
            },
            {
              name: '上班卡：',
              value: `${upTime ? new Date(upTime).toLocaleString() : ''}`,
            },
            {
              name: '下班卡：',
              value: `${downTime ? new Date(downTime).toLocaleString() : ''}`,
            },
            {
              name: '考勤次数：',
              value: `正常${normal || 0}次|旷工${late || 0}次|休息${leave || 0}次`,
            },
            {
              name: '今日工作里程：',
              value: `${workingMileage || 0}km`,
            },
            {
              name: '本月工作时长：',
              value: `${attendanceWorkTime || 0}小时`,
            },
            {
              name: '本月工作天数：',
              value: `${attendanceWorkDay || 0}天`,
            },
            {
              name: '告警信息：',
              value: `${messageValue || ''}`,
              setStyle: (val) => {
                const color = val ? '#CB3F3E' : '#fff';
                return `color:${color};`;
              },
            },
            {
              name: '联系方式：',
              value: `${phone || ''}`,
            },
            {
              name: '定位时间：',
              value: `${time || ''}`,
            },
            {
              name: '查看轨迹',
              type: 'btn',
              mode: 'employees',
            },
          ];
          url = `${mediaBaseUrl}${photo}`;
          break;
        case 'platforms':
          isAbnormal = !!messageValue;
          isAutoH = true;
          // 环卫站
          const {
            maxCapacity,
            capacity,
            disposalToday,
            disposalGrowth,
            disposalThisMonth,
            videoUrls,
          } = data ?? {};
          options = [
            {
              name: '环卫站名称：',
              value: name,
              type: 'name',
            },
            {
              name: '预警状态：',
              value: messageValue || '',
              setStyle: (val) => {
                const color = !val ? 'inherit' : '#CB3F3E';
                return `color:${color};`;
              },
            },
            {
              name: '最大容量：',
              value: `${maxCapacity || 0}m³`,
            },
            {
              name: '已用容量：',
              value: `${capacity || 0}%`,
            },
            {
              name: '今日处理垃圾：',
              value: `${disposalToday || 0}m³`,
            },
            {
              name: '本月处理垃圾：',
              value: `${disposalThisMonth || 0}m³`,
            },
            {
              name: '垃圾总增长量：',
              value: `${disposalGrowth || 0}m³`,
            },
            {
              name: '定位时间：',
              value: `${time || ''}`,
            },
            {
              value: videoUrls,
              type: 'video',
              mode: 'platforms',
            },
            // {
            //   name: '跳转环卫站监控',
            //   type: 'actions',
            // },
          ];
          chartStr = this.setPlatformsChart(capacity, disposalToday, disposalThisMonth, disposalGrowth);
          break;
        case 'buckets':
          // 垃圾桶
          options = [
            {
              name: '垃圾桶名称：',
              value: name,
              type: 'name',
            },
          ];
          break;
        default:
          isAbnormal = !!messageValue;
          // 车辆
          const {
            carNumber,
            driverPhone,
            driver,
          } = data;
          const carNumberStr = carNumber ? `（${carNumber}）` : '';
          options = [
            {
              name: '车辆名称：',
              value: `${name || ''}${carNumberStr}`,
              type: 'name',
            },
            {
              name: '告警信息：',
              value: messageValue || '',
              setStyle: (val) => {
                const color = !val ? 'inherit' : '#CB3F3E';
                return `color:${color};`;
              },
            },
            {
              name: '驾驶人：',
              value: driver || '',
            },
            {
              name: '联系方式：',
              value: driverPhone || '',
            },
            {
              name: '定位时间：',
              value: time || '',
            },
            {
              name: '摄像头：',
              value: isCamera == 1 ? '存在' : '不存在',
              setStyle: (val) => {
                const color = isCamera == 1 ? '#07DF9F' : '#999999';
                return `color:${color};`;
              },
            },
          ];

          // 只有当车辆存在摄像头时才添加视频监控
          if (isCamera == 1 && carNumber) {
            options.push({
              value: carNumber,
              type: 'video',
              mode: 'car',
            });
          }

          // 添加查看轨迹按钮
          options.push({
            name: '查看轨迹',
            type: 'btn',
            mode: 'cars',
          });
          // {
          //   name: '跳转车辆监控',
          //   type: 'actions',
          // },
      }
      if (address) {
        options.push({
          name: '定位地址：',
          value: address,
        })
      }
      // if (messageValue) {
      //   options.push({
      //     name: '警告：',
      //     value: messageValue,
      //     setStyle: (val) => {
      //       return 'color: #ff3d00;';
      //     },
      //   });
      // }

      window.clickPopupBtnHandle = async (target) => {
        const id = target.dataset.id;
        const type = target.dataset.btntype;
        // let route = '';
        // if (!type) return false;
        // if (type === 'cars') route = `/control/carVideo?id=${id}`;
        // if (type === 'platforms') route = `/control/dumpVideo?id=${id}`;
        // window.location.hash = route;
        let data = [];
        let startTime = '', endTime = '';
        if (type === 'employees') {
          const res = await getMapEmployeeList(id);
          data = res.map(item => {
            const { longitude, latitude } = item;
            return [+longitude, +latitude];
          });
          const len = data?.length;
          if (len) {
            endTime = new Date(res[0]?.time).toLocaleString();
            startTime = new Date(res[len - 1]?.time).toLocaleString();
          }
        } else if (type === 'cars') {
          const res = await getMapCarList(id);
          data = res.map(item => {
            const { longitude, latitude } = item;
            return [+longitude, +latitude];
          });
          const len = data?.length;
          if (len) {
            endTime = new Date(res[0]?.time).toLocaleString();
            startTime = new Date(res[len - 1]?.time).toLocaleString();
          }
        }
        if (data.length) {
          // 清除之前的轨迹
          this.closeTrack();

          startTime = `起点${startTime}`;
          endTime = `终点${endTime}`;

          // 高德地图轨迹线
          const polyline = new this.AMap.Polyline({
            path: data.reverse(),
            strokeColor: "#ff6f00",
            strokeWeight: 2,
            strokeOpacity: 1.0,
            strokeStyle: "solid",
            showDir: true
          });
          polyline.setMap(this.map);
          window.trackPolyline = polyline;

          // 添加起点标记
          window.trackMarkers = [];
          if (data.length > 1) {
            const startMarker = new this.AMap.Marker({
              position: data[data.length - 1],
              icon: new this.AMap.Icon({
                image: 'data:image/svg+xml;base64,' + btoa('<svg width="20" height="20"><circle cx="10" cy="10" r="8" fill="#00e676" stroke="#fff" stroke-width="2"/></svg>'),
                size: new this.AMap.Size(20, 20)
              }),
              label: {
                content: startTime,
                direction: 'right'
              }
            });
            startMarker.setMap(this.map);
            window.trackMarkers.push(startMarker);

            // 添加终点标记
            const endMarker = new this.AMap.Marker({
              position: data[0],
              icon: new this.AMap.Icon({
                image: 'data:image/svg+xml;base64,' + btoa('<svg width="20" height="20"><circle cx="10" cy="10" r="8" fill="#f50057" stroke="#fff" stroke-width="2"/></svg>'),
                size: new this.AMap.Size(20, 20)
              }),
              label: {
                content: endTime,
                direction: 'top'
              }
            });
            endMarker.setMap(this.map);
            window.trackMarkers.push(endMarker);
          }

          // 调整视野
          this.map.setFitView([polyline]);
        }
      }

      const btnOptions = options.filter(item => item?.type === 'btn');
      const btnStr = btnOptions.reduce((acc, cur) => {
        const { name } = cur;
        const str = `<div style="cursor: pointer;" class="info-window-box-info-btn" data-id=${id} data-btnType=${type} onclick="clickPopupBtnHandle(this)">${name}</div>`
        acc += str;
        return acc;
      }, '');

      const infoOptions = options.filter(item => !item?.type);
      const infoStr = infoOptions.reduce((acc, cur) => {
        const { name, value, setStyle } = cur;
        const defaultStyle = 'color: #fff;';
        const str = `<div class="info-window-box-info-item" style="${defaultStyle}${setStyle ? setStyle(value) : ''}">
            ${name}${value || ''}
        </div>`
        acc += str;
        return acc;
      }, '');

      const nameInfo = options.filter(item => item?.type === 'name');
      const nameStr = nameInfo.reduce((acc, cur) => {
        const { name, value } = cur;
        const str = `<div class="title-box">${value}</div>`;
        acc += str;
        return acc;
      }, '')

      // 视频监控
      const videoInfo = options.find(item => item?.type === 'video');
      let videoStr = '';
      if (videoInfo) {
        const { value, mode } = videoInfo;
        if (mode === 'car') {
          const res = await getVideoUrl({ carNumber: value });
          const linkUrl = res.data;
          videoStr = `<iframe src="${linkUrl}" frameborder="0" style="width: 100%;height: 100%;" "></iframe>`
        } else if (mode === 'platforms') {
          videoStr = value.reduce((acc, cur) => {
            const url = cur.replace(/^http:\/\/120\.238\.96\.5:8890/, '/another-api');
            const videoItem = `
              <div class="video-item">
                <video class="video-box" muted autoplay controls data-href="${url}"></video>
              </div>
            `;
            acc += videoItem;
            return acc;
          }, '');
        }
      }

      let boxImg = isAbnormal ? red_box : green_box;
      if (['platforms'].includes(type)) boxImg = isAbnormal ? red_long_box : green_long_box;
      const boxStyle = [
        'min-width: 198px',
        'min-height: 292px',
        'max-width: 910px',
      ];
      const content = `
        <div class="info-window-box ${isAbnormal ? 'red' : 'green'}" style="${boxStyle.join(';')}">
           <div class="info-window-box-title">
            <img src="${boxImg}" alt="" />
            ${nameStr}
           </div>
           <div class="info-window-box-info">
             <div class="box">
                ${infoStr}
                ${btnStr}
             </div>
             <div class="chart-box">
                 ${chartStr}
             </div>
           </div>
           <div class="video ${videoStr ? 'show' : ''} ${isAutoH ? 'autoH' : ''}" style="width: 100%;">
                  ${videoStr}
           </div>
        </div>
      `;

      // 创建自定义信息窗口容器
      const infoWindowId = `custom-info-window-${id}-${type}-${Date.now()}`;

      // 检查是否已存在信息窗口，如果存在先关闭
      if (window.currentCustomInfoWindow && window.currentCustomInfoWindow.parentNode) {
        window.currentCustomInfoWindow.parentNode.removeChild(window.currentCustomInfoWindow);
        document.removeEventListener('click', window.currentInfoWindowCloseHandler);
      }

      // 创建信息窗口元素
      const infoWindowEl = document.createElement('div');
      infoWindowEl.id = infoWindowId;
      infoWindowEl.innerHTML = content;
      infoWindowEl.style.cssText = `
        position: fixed;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        z-index: 9999;
        background: rgba(0, 0, 0, 0.7);
        border: 1px solid ${isAbnormal ? '#D36D6D' : '#30A673'};
        border-radius: 8px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
        animation: fadeIn 0.3s ease-out;
      `;

      // 添加CSS动画
      if (!document.getElementById('custom-info-window-styles')) {
        const style = document.createElement('style');
        style.id = 'custom-info-window-styles';
        style.textContent = `
          @keyframes fadeIn {
            from { opacity: 0; transform: translate(-50%, -50%) scale(0.9); }
            to { opacity: 1; transform: translate(-50%, -50%) scale(1); }
          }
        `;
        document.head.appendChild(style);
      }

      // 不立即添加信息窗体，只绑定点击事件
      marker.on('click', () => {
        // 检查是否已经有相同的信息窗口打开
        const isSameWindow = window.currentCustomInfoWindow &&
                           window.currentCustomInfoWindow.id === infoWindowEl.id;

        if (!isSameWindow) {
          // 关闭已存在的信息窗口（如果不同）
          if (window.currentCustomInfoWindow && window.currentCustomInfoWindow.parentNode) {
            window.currentCustomInfoWindow.parentNode.removeChild(window.currentCustomInfoWindow);
          }

          // 添加新的信息窗口
          document.body.appendChild(infoWindowEl);
          window.currentCustomInfoWindow = infoWindowEl;
        }

        // 只在首次打开窗口时创建事件处理函数
        if (!isSameWindow) {
          // 创建点击外部关闭的事件处理函数
          window.currentInfoWindowCloseHandler = (e) => {
            const isClickInside = infoWindowEl.contains(e.target) || marker.getDom().contains(e.target);
            if (!isClickInside) {
              if (infoWindowEl.parentNode) {
                infoWindowEl.parentNode.removeChild(infoWindowEl);
              }
              document.removeEventListener('click', window.currentInfoWindowCloseHandler);
              window.currentCustomInfoWindow = null;
              // 点击其他marker时关闭轨迹
              this.closeTrack();
            }
          };

          // 延迟添加点击外部关闭事件，避免立即触发
          setTimeout(() => {
            document.addEventListener('click', window.currentInfoWindowCloseHandler);
          }, 100);
        }

        // 处理视频
        setTimeout(() => {
          const videoList = document.querySelectorAll('.info-window-box .autoH .video-box');
          if (videoList?.length) {
            videoList.forEach(el => {
              const url = el.getAttribute('data-href');
              if (Hls.isSupported()) {
                const hls = new Hls();
                hls.loadSource(url);
                hls.attachMedia(el);
                hls.on(Hls.Events.MANIFEST_PARSED, () => {
                  el.play().catch(error => {
                    console.warn('Play failed:', error);
                  });
                });
              } else if (el.canPlayType('application/vnd.apple.mpegURL')) {
                el.src = url;
                el.addEventListener('loadedmetadata', () => {
                  el.play().catch(error => {
                    console.warn('Play failed:', error);
                  });
                });
              }
            });
          }
        }, 200);
      });
    },
    createAmapPolygon() {
      // 始终清除旧的Polygon，确保没有残留
      if (this.areaPolygons?.length) {
        this.areaPolygons.forEach(polygon => polygon.setMap(null));
        this.areaPolygons = [];
      }

      // 如果没有区域数据，直接返回
      if (!this.area || !this.area.length) {
        return;
      }

      const data = this.area.reduce((acc, cur) => {
        const { id, name, areaLocations } = cur;
        const path = (areaLocations ?? []).reduce((paths, item) => {
          const { longitude, latitude } = item;
          paths.push([+longitude, +latitude]);
          return paths;
        }, []);

        const polygon = new this.AMap.Polygon({
          path: path,
          strokeColor: '#fff',
          strokeWeight: 2,
          strokeOpacity: 0.8,
          fillColor: '#1791fc',
          fillOpacity: 0.3,
          extData: { id, name }
        });

        // 添加点击事件 - 点击Polygon时关闭所有信息窗口
        polygon.on('click', () => {
          // 关闭高德地图信息窗口
          this.map.clearInfoWindow();
          // 关闭自定义信息窗口
          if (window.currentCustomInfoWindow && window.currentCustomInfoWindow.parentNode) {
            window.currentCustomInfoWindow.parentNode.removeChild(window.currentCustomInfoWindow);
            document.removeEventListener('click', window.currentInfoWindowCloseHandler);
            window.currentCustomInfoWindow = null;
          }
        });

        polygon.setMap(this.map);
        const [longitude, latitude] = this.getPolygonCenter(path);
        // 只在区域切换时触发flyTo，避免数据刷新时触发
        if (this.isAreaChanged && !this.currentAction) {
          this.flyTo({
            data: {
              location: { latitude, longitude }
            }
          });
          this.isAreaChanged = false; // 重置标志
        }
        acc.push(polygon);
        return acc;
      }, []);
      this.areaPolygons = data;
    },
    flyTo(obj) {
      const data = obj?.data ?? {};
      const type = obj?.type ?? "";
      const { location = '' } = data;
      let position = '';
      if (location) {
        const { latitude, longitude } = location;
        position = [+longitude, +latitude];
      } else {
        if (!type) return false;
        const id = data?.id;
        const list = this?.[type] ?? [];
        if (!list?.length) return false;
        const location = list.find(item => item.id == id)?.location ?? "";
        if (!location) return false;
        const { latitude, longitude } = location;
        position = [+longitude, +latitude];
      }
      if (!position) return false;

      // 使用 panTo 实现平滑的动画过渡效果
      this.map.panTo(position);
      this.map.setZoom(16);
    },
    // 绘制人员标记
    drawEmployeesMarker() {
      return this.employees.reduce((acc, cur) => {
        // console.log('人员', cur)
        const { name, photo, id, location, employeeStatus, alarms } = cur;
        const { longitude, latitude } = location;
        let icon = employeeStatus ? employeesRedIcon : employeesGreenIcon;
        const messageValue = (alarms || []).map(item => item?.messageValue || '').join(','); // 警告信息
        if (messageValue) icon = employeesWarnIcon;
        const marker = this.createAmapMarker([longitude, latitude], icon, name, id, cur, 'employees');
        this.addMarkPopup(marker, cur, 'employees');
        acc.push(marker);

        return acc;
      }, []);
    },
    // 绘制车辆
    drawCars() {
      return this.cars.reduce((acc, cur) => {
        // console.log('车辆', cur)
        const { name, id, location, alarms } = cur;
        const { longitude, latitude } = location;
        const icon = alarms?.length ? carsRedIcon : carsGreenIcon;
        const marker = this.createAmapMarker([longitude, latitude], icon, name, id, cur, 'cars');
        this.addMarkPopup(marker, cur, 'cars');
        acc.push(marker);

        return acc;
      }, []);
    },
    // 绘制环卫站
    drawPlatforms() {
      return this.platforms.reduce((acc, cur) => {
        // console.log('环卫站', cur)
        const { name, id, location, alarms } = cur;
        const { longitude, latitude } = location;
        const icon = alarms?.length ? platformsRedIcon : platformsGreenIcon;
        const marker = this.createAmapMarker([longitude, latitude], icon, name, id, cur, 'platforms');
        this.addMarkPopup(marker, cur, 'platforms');
        acc.push(marker);

        return acc;
      }, []);
    },
    drawbuckets() {
      return this.buckets.reduce((acc, cur) => {
        const { name, id, location } = cur;
        const { longitude, latitude } = location;
        const marker = this.createAmapMarker([longitude, latitude], bucketsIcon, name, id, cur, 'buckets');
        this.addMarkPopup(marker, cur, 'buckets');
        acc.push(marker);

        return acc;
      }, []);
    },
    getPolygonCenter(paths) {
      let total = paths.length;
      let X = 0;
      let Y = 0;
      let Z = 0;
      paths.forEach((lnglat) => {
        let lng = lnglat[0] * Math.PI / 180;
        let lat = lnglat[1] * Math.PI / 180;
        let x, y, z;
        x = Math.cos(lat) * Math.cos(lng);
        y = Math.cos(lat) * Math.sin(lng);
        z = Math.sin(lat);
        X += x;
        Y += y;
        Z += z;
      });
      X = X / total;
      Y = Y / total;
      Z = Z / total;

      let Lng = Math.atan2(Y, X);
      let Hyp = Math.sqrt(X * X + Y * Y);
      let Lat = Math.atan2(Z, Hyp);
      return [Lng * 180 / Math.PI, Lat * 180 / Math.PI];
    },
    // 数据刷新后恢复已打开的信息窗口
    restoreOpenInfoWindow() {
      // 如果当前有打开的信息窗口且有记录的currentAction，则恢复窗口
      if (window.currentCustomInfoWindow && this.currentAction) {
        const { data, type } = this.currentAction;
        const { id } = data;

        // 在新的markers中找到对应的marker
        const makers = this?.[`${type}Markers`] || [];
        const currentMarker = makers.find(item => {
          const el = item?.['_element'];
          const currentId = el?.getAttribute('data-id');
          return currentId == id;
        });

        if (currentMarker) {
          // 延迟恢复，确保新的markers已经完全创建
          setTimeout(() => {
            // 检查窗口是否仍然存在（可能被用户手动关闭了）
            if (window.currentCustomInfoWindow && window.currentCustomInfoWindow.parentNode) {
              // 窗口仍然存在，需要更新事件绑定和视频
              const infoWindowEl = window.currentCustomInfoWindow;

              // 重新绑定外部点击事件
              const newInfoWindowCloseHandler = (e) => {
                const isClickInside = infoWindowEl.contains(e.target) || currentMarker.getDom().contains(e.target);
                if (!isClickInside) {
                  if (infoWindowEl.parentNode) {
                    infoWindowEl.parentNode.removeChild(infoWindowEl);
                  }
                  document.removeEventListener('click', newInfoWindowCloseHandler);
                  window.currentCustomInfoWindow = null;
                  this.closeTrack();
                }
              };

              // 更新事件监听器
              document.removeEventListener('click', window.currentInfoWindowCloseHandler);
              window.currentInfoWindowCloseHandler = newInfoWindowCloseHandler;
              setTimeout(() => {
                document.addEventListener('click', newInfoWindowCloseHandler);
              }, 100);

              // 处理视频
              this.refreshVideos();
            } else {
              // 窗口已被关闭，重新打开
              currentMarker.emit('click');
            }
          }, 100);
        }
      }
    },
    // 刷新信息窗口中的视频
    refreshVideos() {
      setTimeout(() => {
        const videoList = document.querySelectorAll('.info-window-box .autoH .video-box');
        if (videoList?.length) {
          videoList.forEach(el => {
            const url = el.getAttribute('data-href');
            if (url && !el.src) {  // 只为未设置src的视频设置
              if (Hls.isSupported()) {
                const hls = new Hls();
                hls.loadSource(url);
                hls.attachMedia(el);
                hls.on(Hls.Events.MANIFEST_PARSED, () => {
                  el.play().catch(error => {
                    console.warn('Play failed:', error);
                  });
                });
              } else if (el.canPlayType('application/vnd.apple.mpegURL')) {
                el.src = url;
                el.addEventListener('loadedmetadata', () => {
                  el.play().catch(error => {
                    console.warn('Play failed:', error);
                  });
                });
              }
            }
          });
        }
      }, 100);
    },
    // 关闭轨迹
    closeTrack() {
      // 清除轨迹线
      if (window.trackPolyline) {
        window.trackPolyline.setMap(null);
        window.trackPolyline = null;
      }

      // 清除起点和终点标记
      if (window.trackMarkers && window.trackMarkers.length) {
        window.trackMarkers.forEach(marker => marker.setMap(null));
        window.trackMarkers = [];
      }
    },
  },
}
</script>

<style scoped lang="scss">
.container {
  height: 100%;
  width: 100%;
  position: relative;

  .map {
    width: 100%;
  }

  .icons {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 52px;
    background-color: rgba(0, 0, 0, 0.5);

    .icon {
      font-size: 11px;
      color: #fff;
      position: relative;

      .name {
        position: absolute;
        top: 44%;
        left: 50%;
        transform: translate(-50%, -50%);
      }
    }

    img {
      height: 25px;
      object-fit: cover;
      margin-right: 20px;
    }
  }
}
</style>
<style lang="scss">
.info-window-box {
  position: relative;
  color: #fff;
  overflow: hidden;
  width: max-content;
  height: max-content;
  border-width: 1px;
  border-style: solid;
  background: rgba(0, 0, 0, 0.7);

  &.red {
    border-color: #D36D6D;
  }

  &.green {
    border-color: #30A673;
  }

  &-title {
    position: relative;
    padding: 4px 24px;
    font-size: 12px;
    color: #fff;
    font-weight: bold;
    z-index: 2;
    text-align: center;
    line-height: 22px;
    height: auto;
    overflow: hidden;

    .title-box {
      color: #fff;
      position: relative;
      z-index: 2;
    }

    img {
      width: 100%;
      object-fit: cover;
      position: absolute;
      top: 50%;
      left: 0;
      transform: translateY(-50%);
    }
  }

  &-close {
    width: 20px;
    height: 20px;
    background-color: rgb(86, 156, 255);
    border-radius: 50%;
    color: #fff;
    font-size: 14px;
    cursor: pointer;
    position: absolute;
    right: 0;
    top: 0;
    transform: translate(50%, -50%);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  &-info {
    position: relative;
    padding: 12px 12px 10px;
    display: flex;
    width: 100%;

    .box {
      flex-shrink: 0;
      min-width: 0;
    }

    .chart-box {
      flex: 1;
      min-width: 0;
      margin-left: 12px;
    }

    &-item {
      display: flex;
      color: #fff;
      font-size: 11px;
      margin-bottom: 8px;
    }

    &-btn {
      cursor: pointer;
      color: #fff;
      width: max-content;
      padding: 4px 10px;
      background-color: #00e676;
      font-size: 11px;
      border-radius: 4px;
    }
  }

  .video {
    position: relative;

    &.show {
      position: relative;

      .video-item {
        margin: 0 6px;
        width: 32%;

        video {
          width: 100%;
        }
      }
    }

    &.autoH {
      height: max-content;
      display: flex;
      flex-wrap: wrap;
    }
  }
}

/* 高德地图信息窗体样式 - 简化版本 */
.amap-info-window-content {
  background-color: transparent;
}

/* 图表项动画效果 */
@keyframes float {

  0%,
  100% {
    transform: translateY(0px);
  }

  50% {
    transform: translateY(-3px);
  }
}

@keyframes pulse {

  0%,
  100% {
    box-shadow: 0 0 0 0 rgba(0, 230, 118, 0.2);
  }

  50% {
    box-shadow: 0 0 0 8px rgba(0, 230, 118, 0.1);
  }
}

@keyframes breathe {

  0%,
  100% {
    transform: scale(1);
  }

  50% {
    transform: scale(1.02);
  }
}

@keyframes glow {

  0%,
  100% {
    filter: brightness(1);
  }

  50% {
    filter: brightness(1.1);
  }
}

.chart-item-hover {
  /* 非悬浮状态的动画 */
  animation: float 3s ease-in-out infinite, pulse 2s ease-in-out infinite;

  img {
    animation: glow 4s ease-in-out infinite;
  }

  /* 为不同的图表项添加延迟，创造波浪效果 */
  &:nth-child(1) {
    animation-delay: 0s, 0s;

    img {
      animation-delay: 0s;
    }
  }

  &:nth-child(2) {
    animation-delay: 0.5s, 0.3s;

    img {
      animation-delay: 0.5s;
    }
  }

  &:nth-child(3) {
    animation-delay: 1s, 0.6s;

    img {
      animation-delay: 1s;
    }
  }

  &:nth-child(4) {
    animation-delay: 1.5s, 0.9s;

    img {
      animation-delay: 1.5s;
    }
  }

  /* 悬浮状态动画 */
  &:hover {
    animation: none;
    /* 悬浮时停止基础动画 */
    transform: translateY(-5px) scale(1.05);
    box-shadow: 0 8px 25px rgba(0, 230, 118, 0.3);
    z-index: 10;

    img {
      animation: none;
      /* 悬浮时停止图片动画 */
      transform: scale(1.1);
    }

    div {
      text-shadow: 0 2px 8px rgba(0, 0, 0, 0.8);
    }
  }

  &:active {
    transform: translateY(-3px) scale(1.02);
    transition: all 0.1s ease;
  }
}
</style>
